package com.neuedu.springbootmy12306.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.neuedu.springbootmy12306.entity.FileResult;
import com.neuedu.springbootmy12306.entity.Goods;
import com.neuedu.springbootmy12306.entity.Pager;
import com.neuedu.springbootmy12306.entity.Result;
import com.neuedu.springbootmy12306.service.GoodsService;
import com.neuedu.springbootmy12306.util.FileuploadUtil;

@Controller
public class GoodsController {
	@Autowired
	private GoodsService goodsServise;

	@RequestMapping("goods/index")
	public String goodsIndex() {
		// 首页只打开页面，不加载数据;页面的数据使用在easy ui中通过ajax技术进行异步加载的
		return "goods/list";
	}

	// easyui请求时使用的是post方法，这里需要使用post方法
	// easy ui进行分页查询时，使用page传递查询的页码，使用rows传递查询的记录数
	@RequestMapping("goods/list")
	@ResponseBody
	public Pager<Goods> goodsList(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = "10") Integer rows) {
		Pager<Goods> pager = new Pager<>(page, rows);
		// 根据查询条件进行分页查询
		List<Goods> goodsList = goodsServise.findListByPager(pager);

		Integer total = goodsServise.findTotalByPager(pager);

		// 把查询到数据保存到pager对象中，再转换成json返回给easy ui
		pager.setRows(goodsList);
		pager.setTotal(total);

		return pager;
	}

	@RequestMapping("goods/add")
	@ResponseBody
	public Result doAdd(MultipartFile imageFile, Goods goods) {

		if (imageFile != null && !imageFile.isEmpty()) {
			FileResult fileResult = FileuploadUtil.uploadFile(imageFile);
			if (!fileResult.getSuccess()) {
				return new Result(false, fileResult.getMsg());
			}
			String serverFile = fileResult.getServerPath();
			goods.setImageUrl(serverFile);
		}

		Result result = goodsServise.add(goods);

		return result;
	}

	@RequestMapping("goods/edit")
	@ResponseBody
	public Result doEdit(MultipartFile imageFile, Goods goods) {
		if (imageFile != null && !imageFile.isEmpty()) {
			FileResult fileResult = FileuploadUtil.uploadFile(imageFile);
			if (!fileResult.getSuccess()) {
				return new Result(false, fileResult.getMsg());
			}
			String serverFile = fileResult.getServerPath();
			goods.setImageUrl(serverFile);
		}

		Result result = goodsServise.edit(goods);
		return result;
	}

	@RequestMapping("goods/delete")
	@ResponseBody
	public Result doDelete(Integer goodsId) {

		List<Goods> list = new ArrayList<Goods>();
		list.add(new Goods(goodsId));

		Result result = goodsServise.deleteByIds(list);
		return result;
	}

}
